<?php
    namespace app\admin\model;
    use think\Model;
    use think\Db;
    
//  model 类
    class AdminModel extends Model
    {
        const ADMINFIELD='admin_id,admin_name,password,login_time,login_ip,admin_type,admin_right';

       
        // 新增管理员 name检查
        public function checkoutAdminName($name){
            $res=Db('admin')->where('admin_name',$name)->find();
            
            return $res?1:0;
        }
        
        // 新建 管理员账户
        /* 
        $arr = array(
            1=>'admin',
            2=>'order'
        ) 参数值需要对应 RightModel中数组key
        */
        public function adminAdd($arr){
            $admin_right=$arr['admin_right'];

            if($arr['admin_type'] == 1){
                $admin_right[]='admin';
            }

            $right=\app\admin\model\RightModel::generateRightByModuleName(array_values($admin_right));

            $data['admin_name']=$arr['admin_name'];
            $data['password']=md5($arr['password1']);
            $data['admin_type']=$arr['admin_type'];
            $data['admin_right']=$right;

            $res=Db('admin')->insert($data);
            if($res){
                return true;
            }else{
                return false;
            }

        }

        // 根据id 获取 管理员信息
        public function getAdminInfoById($id=null,$fields=null){
            if(!$id){
                return false;
            }
            if(!$fields){
                $fields=self::ADMINFIELD;
            }

            $res=Db('admin')->where('admin_id',$id)->field($fields)->find();
            
            return $res?$res:false;
        }

        // 修改管理员信息
        public function adminEdit($arr){
            $admin_right = $arr['admin_right'];
            

            if ($arr['admin_type'] == 1) {
                $admin_right[] = 'admin';
            }
            $right = \app\admin\model\RightModel::generateRightByModuleName(array_values($admin_right));

       
            $data['password'] = self::encryptPassword($arr['password1']);
            $data['admin_type'] = $arr['admin_type'];
            $data['admin_right'] = $right;
            $res = Db('admin')->where('admin_id',$arr['admin_id'])->update($data);
            if ($res) {
                return true;
            } else {
                return false;
            }
        }

        public static function encryptPassword($password)
        {
            $key='hengzheadmin';

            return md5(sha1(crypt($password,$key)));
        }
    }

